<script lang="ts">
import Vue from 'vue'
import NavBar from "@/components/nav-bar/nav-bar.vue";
import Popup from "@/components/popup/popup.vue";
import tips from "@/utils/tips";
import {getTaskStatus, uploadForm} from "@/services/liank";
import {createQRCode} from "@/services/store/storeSettings";
import {PrinterQR} from "@/types/store/printer-qr";

let interval = 0
export default Vue.extend({
  name: "print_qr_code",
  components: {Popup, NavBar},
  data() {
    return {
      QRCode: '',
      printer: {} as PrinterQR,
      printQRCode: false
    }
  },
  computed: {
    lang() {
      return this.$t('storePages.printQRCode')
    },
  },
  destroyed() {
    this.clearPrintInterval()
  },
  onLoad(query?: AnyObject) {
    const printer = JSON.parse(decodeURIComponent(query.printer))
    this.QRCode = this.formatQRCodeUrl(printer.qr_code_url)
    this.printer = printer
  },
  methods: {
    formatQRCodeUrl(url: string): string {
      return url.replace(/\.+\//g, '/')
    },
    // 预览
    openPreviewQRCode() {
      uni.previewImage({current: 1, urls: [this.QRCode]})
    },
    // 保存二维码
    saveQRCode() {
      uni.showLoading({title: '保存中...'})
      console.log("this.QRCode", this.QRCode)
      // TODO 后期优化没有给下载权限的直至需求
      uni.downloadFile({
        url: this.QRCode, // 网络图片 URL
        success: (res) => {
          if (res.statusCode === 200) {
            // 下载成功，保存图片到相册
            uni.saveImageToPhotosAlbum({
              filePath: res.tempFilePath,
              success: () => {
                tips.toast('保存成功', 2000);
              }, fail: (err) => {
                tips.toast('保存失败', 2000);
                console.error('保存失败', err);
              }, complete: () => {
                uni.hideLoading()
              }
            });
          } else {
            tips.toast('下载失败', 2000, 'error')
          }
        },
        fail: (err) => {
          tips.toast('下载失败')
          console.error('下载失败', err);
        }
      });
    },
    async createQRCode() {
      uni.showLoading({title: '加载中...'})
      try {
        const {code, data} = await createQRCode(this.printer.id)
        if (code === 200) {
          this.QRCode = this.formatQRCodeUrl(data.url)
        }
      } finally {
        uni.hideLoading()
      }
    },

    // 打印二维码 确定
    async onPrintQRCodeConFirm() {
      this.printQRCode = false
      uni.showLoading({title: '发送中....'});
      const {QRCode, printer: {port, driver_name, machine: {device_id, device_password}}} = this

      const data = {
        deviceId: device_id,
        printerModel: driver_name, // 打印机型号
        deviceKey: device_password,
        dmPaperSize: 9,
        dmCopies: 1,
        dmDefaultSource: 7,
        jpAutoAlign: 'z5',
        dmColor: 1,
        dmOrientation: 2,
        dmDuplex: 1,
        jobFile: QRCode,
      };
      try {
        const {code, data: {task_id}} = await uploadForm(data)
        console.log("处理单照片上传的响应", data)
        if (code === 200) {
          await this.checkPrintStatus(device_id, device_password, port, task_id)
        }
      } catch (err) {
        console.error('上传失败', err);
        tips.toast('上传失败，请重试');
      }
    },
    async checkPrintStatus(device_id: string, device_password: string, port: string, task_id: string) {
      uni.showLoading({title: '打印中...'})
      interval = setInterval(async () => {
        const {data: {task_state}} = await getTaskStatus(device_id, device_password, port, task_id)

        if (['SUCCESS', 'FAILURE'].includes(task_state)) {
          uni.hideLoading()
          this.clearPrintInterval()
        }
      }, 2000)
    },

    clearPrintInterval() {
      if (interval) {
        clearInterval(interval)
        interval = 0
        uni.hideLoading()
        tips.toast('打印完成', 2000)
      }
    }
  }
})
</script>

<template>
  <view>
    <nav-bar :page-title="lang.pageName"/>
    <view :class="[locale]">
      <view class="card margin-30 padding-40">
        <view class="center" @click="openPreviewQRCode">
          <image :src="QRCode" mode="widthFix"/>
        </view>
        <view class="margin-top-40 gap-30 common-title tags-container">
          <view class="tag" hover-class="hover" @click="saveQRCode">{{ lang.operations['save'] }}</view>
          <view class="tag" @click="createQRCode" hover-class="hover">{{ lang.operations['generate'] }}</view>
          <view class="tag tag-print" @click="printQRCode = true" hover-class="hover">
            {{ lang.operations['print'] }}
          </view>
        </view>
      </view>

      <!-- 重启设备 -->
      <popup :show="printQRCode" @update:show="printQRCode = $event">
        <view class="column gap-40">
          <view class="center common-title">{{ lang.modal['title'] }}</view>
          <!-- 确定 取消 -->
          <view class="flex-between">
            <view class="width-40">
              <u-button :text="otherLang.cancel" style="width: 40rpx" size="large" :plain="true"
                        @click="printQRCode = false"/>
            </view>
            <view class="width-40">
              <u-button type="primary" size="large" @click="onPrintQRCodeConFirm" :text="otherLang.confirm"/>
            </view>
          </view>
        </view>
      </popup>
    </view>
  </view>
</template>

<style scoped lang="scss">
.tags-container {
  display: flex;
  justify-content: flex-end; /* 将内容对齐到右侧 */

  .tag {
    padding: 10rpx 20rpx;
    background-color: #F3F5F9;
    border-radius: 10rpx;
  }

  .tag-print {
    color: white;
    background-color: #0E81FC;
  }
}
</style>